package com.xiaobaibai.handler;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({List.class})
@Component
public class ListTypeHandler implements TypeHandler<List<String>> {

    //入库前的操作
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i,
                             List<String> list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, JSON.toJSONString(list));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        return JSON.parseArray(resultSet.getString(s),String.class);
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        return JSON.parseArray(resultSet.getString(i),String.class);
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return JSON.parseArray(callableStatement.getString(i),String.class);
    }

}
